package me.ywd.api.auth.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author Ye_Wenda
 * @Date 11/6/2017
 */
@Slf4j
@Component
public class AccessFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String accessToken = request.getHeader("accessToken");
        if("123456".equals(accessToken)){
            log.debug("accessToken is ok.");
            return null;
        }
        log.debug("accessToken is not offered or wrong.");
        currentContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        currentContext.setSendZuulResponse(false);
        currentContext.setResponseBody("{\"code\":401,\"message\":\"accessToken is not offered or wrong.\"}");
        return null;
    }
}
